package com.pv.oauth.config;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.Map;


/**
 *
 *  说明：
 *     自定义token授予抽象实现
 *     继承抽象类AbstractTokenGranter，我们也是抽象的，后面好扩展
 *  @author:heshengjin qq:2356899074
 *  @date 2021年2月5日 上午9:51:00
 */
public abstract class CustomAbstractTokenGranter extends AbstractTokenGranter {

    CustomAbstractTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, String grantType) {
        super(tokenServices, clientDetailsService, requestFactory, grantType);
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        Map<String, String> parameters = tokenRequest.getRequestParameters();
        UserDetails loginUser = getUserDetails(parameters);
        if (null == loginUser) {
            throw new InvalidGrantException("账户未找到");
        }
        //Object principal, Object credentials,Collection<? extends GrantedAuthority> authorities
        Authentication userAuth = new UsernamePasswordAuthenticationToken(loginUser,
                loginUser.getPassword(), loginUser.getAuthorities());

        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
        return new OAuth2Authentication(storedOAuth2Request, userAuth);

    }
//
    /**
     * 自定义获取用户信息
     */
    protected abstract UserDetails getUserDetails(Map<String, String> parameters);
}